#!/usr/bin/python
import string
import random
import MySQLdb
import sys 
import datetime
from cgi import parse_qs, escape

def application(environ, start_response):
    request_body_size=int(environ.get('CONTENT_LENGTH', 0)) 
    path_info=environ.get('PATH_INFO', '')    
    path=path_info[1:]
    path=escape(path)
    if path=="":
        if request_body_size==0:
            start_response("400 Bad Request", [("Content-Type", "text/html")])    
            return ["You need a string silly! :D"]
        else:
            url = insertData(environ, request_body_size)
            start_response("303 See Other", [("Location", url)])
            return []
    else:
        sql="SELECT txt from pasteTest where url='%s'" % path
        db=MySQLdb.connect("localhost", "userName", "password", "database")
        cursor=db.cursor()
        cursor.execute(sql)
        start_response("200 OK", [("Content-Type", "text/html")])
        if cursor.rowcount==0:
            start_response("404 Not Found", [('Content-type', 'text/html')])
            return "Invalid URL"
        else:
            for row in cursor.fetchall():
                return [row[0]]

def insertData(environ, request_body_size):
    request_body=environ['wsgi.input'].read(request_body_size)
    d=parse_qs(request_body)
    txt=d.get('txt', [''])[0]
    txt=escape(txt)
    sys.stderr.write(repr((txt)) + "\n")
    db=MySQLdb.connect("localhost", "userName", "password", "database")
    cursor=db.cursor()
    url=id_generator()
    dt=datetime.datetime.now().isoformat()
    sql="INSERT into pasteTest (dt, txt, url) values ('%s', '%s', '%s')" % (dt, txt, url)
    try:
        cursor.execute(sql)
        db.commit()
    except:
        db.rollback()
    db.close()
    link="http://amanda.rivershavewings.net/paste/%s" % url 
    return link


def id_generator(size=6, chars=string.ascii_uppercase+string.digits):
    return ''.join(random.choice(chars) for x in range(size))
                                                                                                                                                                                                                                         1,1           All
